package com.creditcmsplt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.creditcmsplt.common.CommonPhpService;
import com.creditcmsplt.entity.PhpResult;
import com.creditcmsplt.entity.Token;
import com.creditcmsplt.entity.param.CiAuthorReq;
import com.creditcmsplt.entity.param.CiAuthorReqData;
import com.creditcmsplt.entity.param.CiAuthorRsp;
import com.creditcmsplt.entity.param.CiAuthorRspData;
import com.creditcmsplt.entity.param.CiQStatusReq;
import com.creditcmsplt.entity.param.CiQStatusRsp;
import com.creditcmsplt.entity.param.CiQStatusRspData;
import com.creditcmsplt.entity.param.CiUpFileReq;
import com.creditcmsplt.entity.param.CiUpFileReqData;
import com.creditcmsplt.entity.param.CiUpFileReqParam;
import com.creditcmsplt.entity.param.CiUpFileReqSystem;
import com.creditcmsplt.entity.param.CiUpFileRsp;
import com.creditcmsplt.entity.param.CiUpFileRspData;
import com.creditcmsplt.properties.CollectInfoProperties;
import com.creditcmsplt.service.CreditApiService;
import com.creditcmsplt.service.CreditAuothService;
import com.creditcmsplt.service.CreditSysLogService;
import com.creditcmsplt.util.ApplicationVerification;
import com.creditcmsplt.util.AuthorizationVerification;
import com.creditcmsplt.util.BaiduApiUtil;
import com.creditcmsplt.util.Base64Util;
import com.creditcmsplt.util.GZIPUtil;
import com.creditcmsplt.util.RegexUtils;
import com.creditcmsplt.util.TextUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 征信资料上传
 * 
 * @author leiyangjun
 *
 */
@RestController
@RequestMapping("collectInfo")
@Api(value = "collectInfo", tags = { "3.0,非现场版资料收集" },description="collectInfo")
@ApiIgnore
public class CollectInfoController {

	private final Logger log = LoggerFactory.getLogger(CollectInfoController.class);

	@Autowired
	private CreditAuothService creditAuothService;

	@Autowired
	private CollectInfoProperties collectInfoProperties;
	
	@Autowired
	private CommonPhpService phpService;
	
	@Autowired
	private CreditApiService creditApiService;
	
	@Autowired
	private CreditSysLogService creditSysLogService;

	/**
	 * 征信资料上传
	 * 
	 * @return
	 */
	@ApiOperation(value="资料上传(收集--非现场版)",notes="paraminfo:<br/>{<br/>\"system\": {\r\n" + 
			"        \"token\": \"aaaaaaaa\"\r\n" + 
			"    },<br/>\"data\": {\r\n" + 
			"        \"handHoldIdentify\": \"jjdksks(手持身份证照片转换为base64编码)\", \r\n" + 
			"        \"applyFor_type\": \"jpg\", --对于照片的文件格式,如jpg,bmp等\r\n" + 
			"        \"address\": \"深圳市南山区南山街道一号一巷401(通信住址)\", \r\n" + 
			"        \"identify\": \"身份证正面转换为base64编码\", \r\n" + 
			"        \"gender\": \"男(性别)\", \r\n" + 
			"        \"identifyno\": \"42011198910013777(身份证号码)\", \r\n" + 
			"        \"identify_back_type\": \"jpg\", \r\n" + 
			"        \"authority_type\": \"jpg\", \r\n" + 
			"        \"userName\": \"李四(身份证姓名)\", \r\n" + 
			"        \"handHoldIdentify_type\": \"jpg\", \r\n" + 
			"        \"applyFor\": \"查询申请书图,base64编码\", \r\n" + 
			"        \"issuingAuthority\": \"某某公安局某某分局(身份证背后发证机关)\", \r\n" + 
			"        \"certificateExpire\": \"20160104-20360104(身份证有效期,参考身份证背后,去掉.)\", \r\n" + 
			"        \"phoneNumber\": \"158****487(征信人联系号码)\", \r\n" + 
			"        \"authority\": \"授权书图片转换为base64\", \r\n" + 
			"        \"national\": \"汉(民族)\", \r\n" + 
			"        \"identify_type\": \"jpg\", \r\n" + 
			"        \"identify_back\": \"身份证反面照转换为base64编码\", \r\n" + 
			"        \"authorityNumber\": \"200241100011191201711160002(授权书编号)\"--授权书可通过接口下载得到\r\n" + 
			"    }<br/>}")
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) // {paraminfo:""}
	public CiUpFileRsp uploadFile(@RequestBody CiUpFileReqParam params,HttpServletRequest req) {// 获取参数---》base64解密--》解压--》解析json，正常程序
		CiUpFileRsp result=new CiUpFileRsp();
		CiUpFileRspData data=new CiUpFileRspData();
		Integer code=1;
		String msg="提交成功";
		if(params==null||TextUtils.isEmpty(params.getParaminfo())) {
			code=-1;
			msg="必须参数为空";
		}
		String paramInfo=params.getParaminfo();
		byte[] gzipparam = Base64Util.bs64stringToBytes(paramInfo);// 通过base64解码得到压缩后字符
		paramInfo = GZIPUtil.uncompressToString(gzipparam, "UTF-8");
		CiUpFileReq paramObject=JSONObject.toJavaObject(JSONObject.parseObject(paramInfo), CiUpFileReq.class);
		if(paramObject==null) {
			code=-1;
			msg="无法解析参数";
		}
		data=code.equals(1)?checkUploadData(paramObject):data;//校验基础数据，如是否填写、大小尺寸
		code=data!=null&&data.getCode()!=null?data.getCode():code;
		msg=data!=null&&data.getCode()!=null?data.getMsg():msg;
		Map<String, Object> creditAuoth =code.equals(1)?this.creditAuothService.checkToken(paramObject.getSystem().getToken()):new HashMap<String, Object>();
		if(code.equals(1)&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		Token token=code.equals(1)?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code.equals(1)&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String loginToken=code.equals(1)?token.getLogintoken():"";
		if(code.equals(1)&&TextUtils.isEmpty(loginToken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		data=code.equals(1)?checkImagesContent(paramObject, loginToken):data;//扫描校验
		code=data!=null&&data.getCode()!=null?data.getCode():code;
		msg=data!=null&&data.getCode()!=null?data.getMsg():msg;
		
		String apitoken=code.equals(1)?token.getApitoken():"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(apitoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		//校验完毕
		CiUpFileReqData dataParam=code.equals(1)?paramObject.getData():null;
//		if(code.equals(1)) {
//			dataParam.setIdentify_name(UUIDUtil.getUUIDUnline());
//			dataParam.setIdentify_back_name(UUIDUtil.getUUIDUnline());
//			dataParam.setApplyFor_name(UUIDUtil.getUUIDUnline());
//			dataParam.setAuthority_name(UUIDUtil.getUUIDUnline());
//			dataParam.setHandHoldIdentify_name(UUIDUtil.getUUIDUnline());
//			paramObject.setData(dataParam);
//		}
		PhpResult phpResult=code.equals(1)?phpService.uploadIdentify(paramObject, apitoken, ((Long)creditAuoth.get("credit_id"))):new PhpResult();
		String cid=null;
		if(code.equals(1)) {
			code=phpResult.getError()==null||!phpResult.getError().equals(0)?-1:1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"上传身份证正反照失败":phpResult.getReason();
			cid=phpResult.getCid();
		}
		phpResult=code.equals(1)?phpService.uploadInfo(paramObject, cid, apitoken, (String)creditAuoth.get("userid")):new PhpResult();
		if(code.equals(1)) {
			code=phpResult.getError()==null||!phpResult.getError().equals(0)?-1:1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"上传用户信息失败":phpResult.getReason();
		}
		phpResult=code.equals(1)?phpService.uploadOtherFile(paramObject, apitoken, cid):new PhpResult();
		if(code.equals(1)) {
			code=phpResult.getError()==null||!phpResult.getError().equals(0)?-1:1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"上传授权书/申请书/手持证件照失败":phpResult.getReason();
		}
		//删除临时图片
//		if(dataParam!=null) {
//			FileUtil.deleteFiles(collectInfoProperties.getImagesPath() + dataParam.getAuthority_name() + "."+ dataParam.getAuthority_type(),
//					collectInfoProperties.getImagesPath() + dataParam.getApplyFor_name() + "."+ dataParam.getApplyFor_type(),
//					collectInfoProperties.getImagesPath() + dataParam.getIdentify_name() + "."+ dataParam.getIdentify_type(),
//					collectInfoProperties.getImagesPath() + dataParam.getIdentify_back_name() + "."+ dataParam.getIdentify_back_type(),
//					collectInfoProperties.getImagesPath() + dataParam.getHandHoldIdentify_name() + "."+ dataParam.getHandHoldIdentify_type());
//			creditApiService.insert(paramObject.getSystem().getToken(), "", "", code, req.getServletPath());
//		}
		creditApiService.insert(paramObject.getSystem().getToken(), "", "", code, req.getServletPath());
		data.setCode(code);
		data.setMsg(msg);
		result.setData(data);
		return result;
	}
	
	private CiUpFileRspData checkUploadData(CiUpFileReq params) {
		CiUpFileRspData result=new CiUpFileRspData();
		result.setCode(1);
		result.setMsg("成功");
		CiUpFileReqSystem sys=params.getSystem();
		CiUpFileReqData data=params.getData();
		if(sys==null||TextUtils.isEmpty(sys.getToken())) {
			result.setCode(-1);
			result.setMsg("缺少授权参数system部分");
		}
		if(data==null&&result.getCode().equals(1)) {//减少代码嵌套太多if
			result.setCode(-1);
			result.setMsg("缺少业务数据data部分");
		}
		if(result.getCode().equals(1)&&(
				TextUtils.isEmpty(data.getIdentify())||
				TextUtils.isEmpty(data.getIdentify_type())||
				TextUtils.isEmpty(data.getIdentify_back())||
				TextUtils.isEmpty(data.getIdentify_back_type()))) {
			result.setCode(-1);
			result.setMsg("缺少身份证正反照信息");
		}
		if(result.getCode().equals(1)&&(
				TextUtils.isEmpty(data.getAuthority())||
				TextUtils.isEmpty(data.getAuthority_type())||
				TextUtils.isEmpty(data.getApplyFor())||
				TextUtils.isEmpty(data.getApplyFor_type()))) {
			result.setCode(-1);
			result.setMsg("缺少授权书/申请书信息");
		}
		if(result.getCode().equals(1)&&(
				TextUtils.isEmpty(data.getHandHoldIdentify())||
				TextUtils.isEmpty(data.getHandHoldIdentify_type()))) {
			result.setCode(-1);
			result.setMsg("缺少手持证件照");
		}
		if(result.getCode().equals(1)&&TextUtils.isEmpty(data.getAuthorityNumber())) {
			result.setCode(-1);
			result.setMsg("缺少授权书编号");
		}
		if(result.getCode().equals(1)&&(TextUtils.isEmpty(data.getUserName())||
				TextUtils.isEmpty(data.getGender())||
				TextUtils.isEmpty(data.getNational())||
				TextUtils.isEmpty(data.getAddress())||
				TextUtils.isEmpty(data.getIssuingAuthority())||
				TextUtils.isEmpty(data.getCertificateExpire())||
				TextUtils.isEmpty(data.getPhoneNumber())||
				TextUtils.isEmpty(data.getIdentifyno()))) {
			result.setCode(-1);
			result.setMsg("被征信人信息为必须项(包含:姓名、性别、名族、地址、证件有效期、证件签发机关、身份照吗、手机)");
		}
		if(result.getCode().equals(1)&&!RegexUtils.checkPhone(data.getPhoneNumber())) {//校验手机号码合法性
			result.setCode(-1);
			result.setMsg("被征信人手机号码必须是11位正确手机号码");
		}
		if(result.getCode().equals(1)&&checkFileSize(data.getIdentify())) {
			result.setCode(-1);
			result.setMsg("身份证正面照不能超过最大2M限制");
		}
		if(result.getCode().equals(1)&&checkFileSize(data.getIdentify_back())) {
			result.setCode(-1);
			result.setMsg("身份证反面照不能超过最大2M限制");
		}
		if(result.getCode().equals(1)&&checkFileSize(data.getAuthority())) {
			result.setCode(-1);
			result.setMsg("授权书不能超过最大2M限制");
		}
		if(result.getCode().equals(1)&&checkFileSize(data.getApplyFor())) {
			result.setCode(-1);
			result.setMsg("申请书不能超过最大2M限制");
		}
		if(result.getCode().equals(1)&&checkFileSize(data.getHandHoldIdentify())) {
			result.setCode(-1);
			result.setMsg("手持证件照不能超过最大2M限制");
		}
		return result;
	}
	
	private CiUpFileRspData checkImagesContent(CiUpFileReq params,String logintoken) {
		CiUpFileRspData result=new CiUpFileRspData();
		result.setCode(1);
		result.setMsg("成功");
		CiUpFileReqData data=params.getData();
		JSONObject idcardZJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.idcardRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getIdentify()),true,logintoken):null;
		if(result.getCode().equals(1)&&((idcardZJson==null||idcardZJson.get("words_result")==null)||(idcardZJson!=null&&idcardZJson.get("error_code")!=null))) {//error_code
			result.setCode(-1);
			result.setMsg("获取身份证正面照信息失败，请确保照片无反光，保持照片清晰度。以及确保图片能正常预览");
		}
		if(result.getCode().equals(1)&&idcardZJson.getJSONObject("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONObject wordsJson= idcardZJson.getJSONObject("words_result");
			JSONObject nameJson=wordsJson.getJSONObject("姓名");
			String userName=nameJson.getString("words");
			if(result.getCode().equals(1)&&!data.getUserName().equals(userName)) {
				log.warn(" check idcard info userName:"+data.getUserName()+"---"+userName);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，如果一致，请确保照片清晰度，无反光（姓名）");
			}
			JSONObject genderJson=wordsJson.getJSONObject("性别");
			String gender=genderJson.getString("words");
			if(result.getCode().equals(1)&&!data.getGender().equals(gender)) {
				log.warn(" check idcard info gender:"+data.getGender()+"---"+gender);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，请确保照片清晰度，无反光（性别）");
			}
			JSONObject nationalJson=wordsJson.getJSONObject("民族");
			String national=nationalJson.getString("words");
			if(result.getCode().equals(1)&&!data.getNational().equals(national)) {
				log.warn(" check idcard info national:"+data.getNational()+"---"+national);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，请确保照片清晰度，无反光（名族）");
			}
			
			JSONObject identifynoJson=wordsJson.getJSONObject("公民身份号码");
			String identifyno=identifynoJson.getString("words");
			if(result.getCode().equals(1)&&!data.getIdentifyno().equals(identifyno)) {
				log.warn(" check idcard info identifyno:"+data.getIdentifyno()+"---"+identifyno);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，请确保照片清晰度，无反光（证件号码）");
			}
		}
		JSONObject idcardFJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.idcardRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getIdentify_back()),false,logintoken):null;
		if(result.getCode().equals(1)&&((idcardFJson==null||idcardFJson.get("words_result")==null)||(idcardFJson!=null&&idcardFJson.get("error_code")!=null))) {
			result.setCode(-1);
			result.setMsg("获取身份证反面照信息失败，请确保照片无反光，保持照片清晰度。以及确保文件问正确的可读取图片文件");
		}
		if(result.getCode().equals(1)&&idcardFJson.getJSONObject("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONObject wordsJson= idcardFJson.getJSONObject("words_result");
			JSONObject issuingAuthorityJson=wordsJson.getJSONObject("签发机关");
			String issuingAuthority=issuingAuthorityJson.getString("words");
			if(result.getCode().equals(1)&&!data.getIssuingAuthority().equals(issuingAuthority)) {
				log.warn(" check idcard info issuingAuthority:"+data.getIssuingAuthority()+"---"+issuingAuthority);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，请确保照片清晰度，无反光（证件签发机关）");
			}
			JSONObject certificateExpireJson=wordsJson.getJSONObject("签发日期");
			String certificateExpire=certificateExpireJson.getString("words")+"-"+wordsJson.getJSONObject("失效日期").getString("words");
			if(result.getCode().equals(1)&&!data.getCertificateExpire().equals(certificateExpire)) {
				log.warn(" check idcard info certificateExpire:"+data.getCertificateExpire()+"---"+certificateExpire);
				result.setCode(-1);
				result.setMsg("证件信息和被征信人信息不一致，请确保照片清晰度，无反光（证件有效期）");
			}
		}
		JSONObject idcardZNumFJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.generalRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getIdentify()),logintoken):null;
		if(result.getCode().equals(1)&&((idcardZNumFJson==null||idcardZNumFJson.get("words_result")==null)||(idcardZNumFJson!=null&&idcardZNumFJson.get("error_code")!=null))) {
			result.setCode(-1);
			result.setMsg("获取身份证正面照信息失败，请确保照片无反光，保持照片清晰度。以及确保文件问正确的可读取图片文件");
		}
		if(result.getCode().equals(1)&&idcardZNumFJson.getJSONArray("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONArray wordsJson= idcardZNumFJson.getJSONArray("words_result");
			String authorityNumber=wordsJson.getJSONObject(0).getString("words");
			authorityNumber=authorityNumber.substring(authorityNumber.indexOf(":")+1, authorityNumber.length());
			if(result.getCode().equals(1)&&!authorityNumber.equals(data.getAuthorityNumber())) {//编号:28827372382832
				log.warn(" check idcard info authorityNumber:"+data.getAuthorityNumber()+"---"+authorityNumber);
				result.setCode(-1);
				result.setMsg("身份证正面置于申请书或授权书下方，不要遮挡编号，且授权书编号必须和传入授权书编号一致.如果是一致，请确保上传图片清晰度");
			}
		}
		JSONObject idcardFNumFJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.generalRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getIdentify_back()),logintoken):null;
		if(result.getCode().equals(1)&&((idcardFNumFJson==null||idcardFNumFJson.get("words_result")==null)||(idcardFNumFJson!=null&&idcardFNumFJson.get("error_code")!=null))) {
			result.setCode(-1);
			result.setMsg("获取身份证反面照信息失败，请确保照片无反光，保持照片清晰度。以及确保文件问正确的可读取图片文件");
		}
		if(result.getCode().equals(1)&&idcardFNumFJson.getJSONArray("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONArray wordsJson= idcardFNumFJson.getJSONArray("words_result");
			String authorityNumber=wordsJson.getJSONObject(0).getString("words");
			authorityNumber=authorityNumber.substring(authorityNumber.indexOf(":")+1, authorityNumber.length());
			if(result.getCode().equals(1)&&!authorityNumber.equals(data.getAuthorityNumber())) {
				log.warn(" check idcard info authorityNumber:"+data.getAuthorityNumber()+"---"+authorityNumber);
				result.setCode(-1);
				result.setMsg("身份证反面置于申请书或授权书下方，不要遮挡编号，且授权书编号必须和传入授权书编号一致.如果是一致，请确保上传图片清晰度");
			}
		}
		JSONObject authorityNumFJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.generalRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getAuthority()),logintoken):null;
		if(result.getCode().equals(1)&&((authorityNumFJson==null||authorityNumFJson.get("words_result")==null)||(authorityNumFJson!=null&&authorityNumFJson.get("error_code")!=null))) {
			result.setCode(-1);
			result.setMsg("授权书扫描失败，请判断是否为受支持的正确的图片文件.");
		}
		String authorStr="";
		if(result.getCode().equals(1)&&authorityNumFJson.getJSONArray("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONArray wordsJson= authorityNumFJson.getJSONArray("words_result");
			String authorityNumber=wordsJson.getJSONObject(1).getString("words");
			authorityNumber=authorityNumber.substring(authorityNumber.indexOf(":")+1, authorityNumber.length());
			if(result.getCode().equals(1)&&!authorityNumber.equals(data.getAuthorityNumber())) {
				log.warn(" check idcard info authorityNumber:"+data.getAuthorityNumber()+"---"+authorityNumber);
				result.setCode(-1);
				result.setMsg("授权书编号必须和授权书图片上编号一致，如果是一致，请确保上传图片清晰度.");
			}
			for (int i=0;i<wordsJson.size();i++) {
				String rn="\r\n";
				rn=i==wordsJson.size()-1?"":rn;
				authorStr+=wordsJson.getJSONObject(i).getString("words")+rn;
			}
		}
		
		JSONObject applyForNumFJson=result.getCode().equals(1)?BaiduApiUtil.INSTANCE.generalRecognition(collectInfoProperties,Base64Util.bs64stringToBytes(data.getApplyFor()),logintoken):null;
		if(result.getCode().equals(1)&&(applyForNumFJson==null||applyForNumFJson.getJSONArray("words_result")==null)) {
			result.setCode(-1);
			result.setMsg("申请书扫描失败，请判断是否为受支持的正确的图片文件.");
		}
		String applyStr="";
		if(result.getCode().equals(1)&&applyForNumFJson.getJSONArray("words_result")!=null) {//校验身份证和所填写是否合法,姓名，性别
			JSONArray wordsJson= applyForNumFJson.getJSONArray("words_result");
			String authorityNumber=wordsJson.getJSONObject(1).getString("words");
			authorityNumber=authorityNumber.substring(authorityNumber.indexOf(":")+1, authorityNumber.length());
			if(result.getCode().equals(1)&&!authorityNumber.equals(data.getAuthorityNumber())) {
				log.warn(" check idcard info authorityNumber:"+data.getAuthorityNumber()+"---"+authorityNumber);
				result.setCode(-1);
				result.setMsg("申请书编号必须和申请书编号上编号一致，如果是一致，请检查照片是否旋转.");
			}
			for (int i=0;i<wordsJson.size();i++) {
				String rn="\r\n";
				rn=i==wordsJson.size()-1?"":rn;
				applyStr+=wordsJson.getJSONObject(i).getString("words")+rn;
			}
		}
		ApplicationVerification applicationVerification=new ApplicationVerification();
		if(result.getCode().equals(1)&&!applicationVerification.hasFillInIegally(applyStr)) {
			result.setCode(-1);
			result.setMsg("申请书空白部分必须由本人填写，并签字按手印");
		}
		AuthorizationVerification authorizationVerification=new AuthorizationVerification();
		if(result.getCode().equals(1)&&!authorizationVerification.hasFillInIegally(authorStr)) {
			result.setCode(-1);
			result.setMsg("授权书空白部分必须由本人填写，并签字按手印");
		}
		return result;
	}
	
	/**
	 * 校验文件大小，是否超过规定的3M
	 * @param base64:base64文件内容
	 * @return 超过返回true，没超过返回false
	 */
	private boolean checkFileSize(String base64) {
		byte[] bytes=Base64Util.bs64stringToBytes(base64);
		//3000000
		return bytes.length>2000000?true:false;
		
	}
	
	/**
	 * 征信状态查询
	 * 
	 * @return
	 */
	@ApiOperation(value="状态查询",notes="资料收集完成后(上传后)成功后,可以通过该接口查询状态能够获知报告是否生成下发")
	@RequestMapping(value = "/queryStatus", method = RequestMethod.POST)
	public CiQStatusRsp queryStatus(@RequestBody CiQStatusReq params,HttpServletRequest req) {
		CiQStatusRsp result=new CiQStatusRsp();
		Integer code=1;
		String msg="成功";
		if(params.getSystem()==null||TextUtils.isEmpty(params.getSystem().getToken())) {
			code=-1;
			msg="token为空";
		}
		if(code.equals(1)&&(params.getData()==null||TextUtils.isEmpty(params.getData().getIdentify()))) {
			code=-1;
			msg="查询身份证号码为空";
		}
		Map<String, Object> creditAuoth =code.equals(1)?this.creditAuothService.checkToken(params.getSystem().getToken()):new HashMap<String, Object>();
		if(code.equals(1)&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String logintoken=code.equals(1)?phpService.getLogin((String)creditAuoth.get("userid"), (String)creditAuoth.get("password")):"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(logintoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code.equals(1)?phpService.queryStatus(logintoken, params.getData().getIdentify()):new PhpResult();
		if(code.equals(1)&&phpResult!=null) {
			code=phpResult.getError().equals(0)?phpResult.getStatus():-1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"查询成功":phpResult.getReason();
		}
		
		CiQStatusRspData data=new CiQStatusRspData();
		data.setCode(code);
		data.setMsg(msg);
		result.setData(data);
		creditApiService.insert(params.getSystem().getToken(), "", "", code, req.getServletPath());
		return result;
	}
	
	/**
	 * 授权书下载
	 * @param res
	 * @throws IOException
	 */
	@ApiImplicitParams({
        @ApiImplicitParam(name = "applyid", value = "申请标识，由/appAuthority返回", required = true,paramType="query" ),
        @ApiImplicitParam(name = "token", value = "厂商授权码，由api/getToken获取", required = true,paramType="query")
	})
	@ApiOperation(value="授权书下载",notes="通过授权书申请后,可以通过该接口下载授权书,参数为?applyid=申请时返回的applyid&token=aaa")
	@RequestMapping(value = "/downloadAuthority", method = RequestMethod.GET)
	public void downloadAuthority(@RequestParam("applyid") String applyid,@RequestParam("token") String token,HttpServletRequest req, HttpServletResponse res) throws Exception {
		//String applyid = req.getParameter("applyid");
		//String token = req.getParameter("token");
		Integer code=1;
		String msg="";
		Map<String, Object> creditAuoth =code.equals(1)?this.creditAuothService.checkToken(token):new HashMap<String, Object>();
		if(code.equals(1)&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		Token tokenObject=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code.equals(1)&&tokenObject==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String logintoken=code==1?tokenObject.getLogintoken():"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(logintoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String apitoken=code==1?tokenObject.getApitoken():"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(apitoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		PhpResult phpResult=code.equals(1)?phpService.authorPdfDown(apitoken, applyid):new PhpResult();
		String filePath="";
		if(code.equals(1)&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"查询成功":phpResult.getReason();
			filePath=phpResult.getFile();
		}
		if(code.equals(1)) {
			File file = new File(filePath);
			code=file.exists()?1:-1;
			msg="找不到文件";
		}
		if(code.equals(1)) {
			res.setCharacterEncoding("UTF-8");
			res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
			res.setContentType("application/octet-stream");
			res.setHeader("Content-Disposition", "attachment;filename=" + filePath.substring(filePath.lastIndexOf("/"), filePath.length()));
			File file = new File(filePath);
			FileInputStream fin = new FileInputStream(file);
			res.setContentLengthLong(file.length());
			OutputStream outputStream = res.getOutputStream();
			byte[] buff = new byte[1024];
			int i = fin.read(buff);
			while (i != -1) {
				outputStream.write(buff, 0, buff.length);
				outputStream.flush();
				i = fin.read(buff);
			}
			fin.close();
			phpService.changeStatus(apitoken, applyid);
		}else {
			res.setCharacterEncoding("UTF-8");
			res.setHeader("Content-type", "text/json;charset=UTF-8");
			JSONObject resultJson = new JSONObject();
			JSONObject dataJson = new JSONObject();
			dataJson.put("code", code);
			dataJson.put("msg", msg);
			resultJson.put("data", dataJson);
			res.getWriter().println(resultJson);
		}
		creditApiService.insert(token, "", "", code, req.getServletPath());
	}
	
	/**
	 * 授权书申请
	 * 
	 * @return
	 */
	@ApiOperation(value="授权书申请",notes="获取授权书,授权书是资料收集时必要资料")
	@RequestMapping(value = "/appAuthority", method = RequestMethod.POST)
	public CiAuthorRsp applyAuthority(@RequestBody CiAuthorReq params,HttpServletRequest req) {
		CiAuthorRsp result=new CiAuthorRsp();
		//CollectApplyAuthorDataRspInfo data=new CollectApplyAuthorDataRspInfo();
		Integer code=1;
		String msg="成功";
		if(params.getSystem()==null||TextUtils.isEmpty(params.getSystem().getToken())) {
			code=-1;
			msg="token为空";
		}
		if(code.equals(1)&&(params.getData()==null||params.getData().getNum()==null)) {
			CiAuthorReqData dataTemp=params.getData();
			dataTemp.setNum(1);
			params.setData(dataTemp);
		}
		Map<String, Object> creditAuoth =code.equals(1)?this.creditAuothService.checkToken(params.getSystem().getToken()):new HashMap<String, Object>();
		if(code.equals(1)&&(creditAuoth==null||creditAuoth.get("userid")==null)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		Token token=code==1?creditSysLogService.getToken((Long)creditAuoth.get("credit_id")):null;
		if(code==1&&token==null) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String logintoken=code==1?token.getLogintoken():"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(logintoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String apitoken=code==1?token.getApitoken():"";//2.8api token
		if(code.equals(1)&&TextUtils.isEmpty(apitoken)) {
			code=-1;
			msg="token过期，请重新获取token";
		}
		String applyid="";
		PhpResult phpResult=code.equals(1)?phpService.appAuthority(apitoken, params.getData().getNum(), creditAuoth.get("credit_id").toString()):new PhpResult();
		if(code.equals(1)&&phpResult!=null) {
			code=phpResult.getError().equals(0)?1:-1;
			msg=TextUtils.isEmpty(phpResult.getReason())?"申请成功":phpResult.getReason();
			applyid=TextUtils.isEmpty(phpResult.getApplyid())?"":phpResult.getApplyid();
		}
		
		CiAuthorRspData data=new CiAuthorRspData();
		data.setApplyid(applyid);
		data.setCode(code);
		data.setMsg(msg);
		result.setData(data);
		creditApiService.insert(params.getSystem().getToken(), "", "", code, req.getServletPath());
		return result;
	}
}
